package dxunderground.winampController.Client;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.DefaultListModel;
import javax.swing.JLabel;

public class Client {
	private PrintWriter out;
	private BufferedReader in;
	public boolean connection;
	public static String host = "ACER";

	public Client() {
		try {
			Socket socket = new Socket(host, 4444);
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			connection = true;
		} catch (UnknownHostException e) {
			System.err.println("Don't know about host: " + host);
			connection = false;
		} catch (IOException e) {
			System.err.println("Couldn't get I/O for the connection to: " + host);
			connection = false;
		}
	}

	public void quit() {
		out.println("__END__");
	}

	public void add(String song) {
		out.println("<Add>" + song + "</Add>");
		try {
			in.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void action(String action) {
		out.println("<" + action + "/>");
		try {
			in.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void getPlaylist(DefaultListModel listModel, JLabel statusLabel, Playlist playlist) {
		out.println("Get Playlist");
		try {
			String song = in.readLine();
			if (song.equals("<Songs>")) {
				song = in.readLine();
			}
			while (!song.equals("</Songs>")) {
				listModel.addElement(song);
				playlist.add(new File(song));
				song = in.readLine();
			}
			statusLabel.setText(listModel.size() + "");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}